package com.coder306.shiro;

import java.io.Serializable;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.subject.Subject;

import com.coder306.util.RedisUtil;
import com.coder306.util.SerializableUtil;

public class UpmsSessionDao extends CachingSessionDAO {

	public static final String UPMS_SHIRO_SESSION_ID = "upms-shiro-session-id";

	// 全局会话列表key
	private final static String UPMS_SERVER_SESSION_IDS = "upms-server-session-ids";

	/**
	 * 更新session
	 */
	@Override
	protected void doUpdate(Session session) {
		// 如果会话过期/停止 没必要再更新了
        if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
            return;
        }
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
        	System.out.println("登陆");
        }
        // 更新session的最后一次访问时间
        RedisUtil.set(UPMS_SHIRO_SESSION_ID + "-" + session.getId(), SerializableUtil.serialize(session), (int) session.getTimeout()/1000);
	}

	/**
	 * 删除Session
	 */
	@Override
	protected void doDelete(Session session) {
		String sessionId = session.getId().toString();
        // 删除session
        RedisUtil.remove(UPMS_SHIRO_SESSION_ID + "-" + sessionId);
	}

	/**
	 * 创建Session
	 */
	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		RedisUtil.set(UPMS_SHIRO_SESSION_ID + "-" + sessionId, SerializableUtil.serialize(session),
				(int) session.getTimeout() / 1000);
		return sessionId;
	}

	/**
	 * 读取session
	 */
	@Override
	protected Session doReadSession(Serializable sessionId) {
		String session = RedisUtil.get(UPMS_SHIRO_SESSION_ID + "-" + sessionId);
        return SerializableUtil.deserialize(session);
	}

}
